package com.ynqxg.router.processor

import com.google.devtools.ksp.processing.Dependencies
import com.google.devtools.ksp.processing.Resolver
import com.google.devtools.ksp.processing.SymbolProcessor
import com.google.devtools.ksp.processing.SymbolProcessorEnvironment
import com.google.devtools.ksp.symbol.KSAnnotated
import com.google.devtools.ksp.symbol.KSClassDeclaration
import java.io.OutputStream

class RouterProcessor(private val environment: SymbolProcessorEnvironment) :
    SymbolProcessor {
    companion object {
        const val ROOT_CLASS_NAME = "Router"
    }

    override fun process(resolver: Resolver): List<KSAnnotated> {
        // 获取需要注册Router的类
        val routerActivityClass = resolver
            .getSymbolsWithAnnotation(Router::class.java.name)
            .filterIsInstance<KSClassDeclaration>()

        val classList = mutableListOf<String>()
        routerActivityClass.toList().forEach { clazz ->
            clazz.accept(RouterKspVisitor(environment) {
                classList.add(it)
            }, Unit)
        }
        val outputStream: OutputStream?
        val moduleName = environment.options["module"] ?: "app${System.currentTimeMillis()}"
        val packageName = "router.register.$moduleName"
        try {
            val codeGenerator = environment.codeGenerator
            outputStream = codeGenerator.createNewFile(
                Dependencies.ALL_FILES,
                packageName,
                "RegisterRouter"
            )
        } catch (e: FileAlreadyExistsException) {
            return emptyList()
        }
        try {
            outputStream.write("package $packageName\n".toByteArray())
            outputStream.write("\n".toByteArray())
            outputStream.write("\n".toByteArray())
            outputStream.write("class RegisterRouter {\n".toByteArray())
            outputStream.write("\n".toByteArray())
            outputStream.write("   init {\n".toByteArray())
            classList.forEach {
                outputStream.write("       ${it}()\n".toByteArray())
            }
            outputStream.write("   }\n".toByteArray())
            outputStream.write("\n".toByteArray())
            outputStream.write("}".toByteArray())
            outputStream.flush()
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            outputStream.close()
        }
        return emptyList()
    }


}